package com.zjj;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;

@Component
public class AccessFilter extends ZuulFilter {

	private static Logger log = LoggerFactory.getLogger(AccessFilter.class);

	@Override
	public Object run() throws ZuulException {
		RequestContext ctx = RequestContext.getCurrentContext();
		HttpServletRequest request = ctx.getRequest();

		log.info(String.format("%s request %s", request.getMethod(), request.getRequestURL().toString()));

		Object token = request.getParameter("token");
		if (token == null) {
			log.warn("token is empty");
			// 过滤该请求，不对其进行路由
			ctx.setSendZuulResponse(false);
			// 相应请求错误的内容
			ctx.setResponseBody("{\"result\":\"token is not null\"}");
			ctx.setResponseStatusCode(401);
			return null;
		}
		log.info("success");
		return null;
	}

	@Override
	public boolean shouldFilter() {
		return true;
	}

	@Override
	public int filterOrder() {
		return 0;
	}

	@Override
	public String filterType() {
		return "pre";
	}

}
